package com.jiulan.hearthearing.ui.login.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.jiulan.hearthearing.R;
import com.jiulan.hearthearing.base.BaseActivity;
import com.jiulan.hearthearing.base.BaseModel;
import com.jiulan.hearthearing.common.MethodUtils;
import com.jiulan.hearthearing.constants.UrlConstants;
import com.jiulan.hearthearing.http.HttpRequest;
import com.jiulan.hearthearing.http.HttpStringCallBack;
import com.jiulan.hearthearing.ui.login.model.LoginModel;
import com.jiulan.hearthearing.utils.SoftKeyboardUtils;
import com.jiulan.hearthearing.utils.StringUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * 验证码登录
 */
public class LoginVerificationCodeActivity extends BaseActivity implements View.OnClickListener {
    private String phone = "", code = "";
    private static final int CODE_ING = 1;//已发送，倒计时
    private static final int CODE_REPEAT = 2;//重新发送
    private int TIME = 60;// 倒计时60s

    private EditText etLoginPhone;
    private EditText etLoginCode;
    private ImageView ivClear;
    private TextView tvGetCode;
    private TextView tvLogin;
    private TextView goPasswordLogin;
    private TextView goRegister;
    private ImageView ivWechatLogin;
    private ImageView ivQQLogin;
    private ImageView ivWeiboLogin;

    public static void actionStart(Context context, String phone) {
        Intent intent = new Intent(context, LoginVerificationCodeActivity.class);
        intent.putExtra("phone", phone);
        context.startActivity(intent);
    }

    @Override
    protected void init(Bundle savedInstanceState) {
        setAndroidNativeLightStatusBar(true);
    }

    @Override
    protected int setLayoutResourceID() {
        return R.layout.activity_login_verification_code;
    }

    @Override
    protected void initView() {
        phone = getIntent().getStringExtra("phone");
        etLoginPhone = findViewById(R.id.etLoginPhone);
        etLoginCode = findViewById(R.id.etLoginCode);
        ivClear = findViewById(R.id.ivClear);
        tvGetCode = findViewById(R.id.tvGetCode);
        tvLogin = findViewById(R.id.tvLogin);
        goPasswordLogin = findViewById(R.id.goPasswordLogin);
        goRegister = findViewById(R.id.goRegister);
        ivWechatLogin = findViewById(R.id.ivWechatLogin);
        ivQQLogin = findViewById(R.id.ivQQLogin);
        ivWeiboLogin = findViewById(R.id.ivWeiboLogin);
        ivClear.setOnClickListener(this);
        tvGetCode.setOnClickListener(this);
        tvLogin.setOnClickListener(this);
        goPasswordLogin.setOnClickListener(this);
        goRegister.setOnClickListener(this);
        ivWechatLogin.setOnClickListener(this);
        ivQQLogin.setOnClickListener(this);
        ivWeiboLogin.setOnClickListener(this);
        etLoginPhone.setText(phone);
        etLoginPhone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                try {
                    phone = s.toString().trim();
                } catch (Exception e) {
                    phone = "";
                }
                checkInput();
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        etLoginCode.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                try {
                    code = s.toString().trim();
                } catch (Exception e) {
                    code = "";
                }
                checkInput();
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    @Override
    protected void initData() {

    }

    @Override
    public int getTitleBarType() {
        return TITLEBAR_DEFAULT;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ivClear://一键删除手机号
                etLoginPhone.setText("");
                break;
            case R.id.tvGetCode://获取验证码
                if (StringUtils.isPhoneNumber(phone)) {
                    getMobileMsgCode();
                } else {
                    Toast.makeText(this, "请填写正确的手机号码", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.goPasswordLogin://go密码登录界面
                LoginPasswordActivity.actionStart(getContext(), phone);
                finish();
                break;
            case R.id.goRegister://go注册界面
                RegisterActivity.actionStart(getContext());
                break;
            case R.id.tvLogin://登录
                SoftKeyboardUtils.hideSoftKeyboard(this);
                login();
                break;
            case R.id.ivWechatLogin://微信登录
                break;
            case R.id.ivQQLogin://QQ登录
                break;
            case R.id.ivWeiboLogin://微博登录
                break;
        }
    }

    private void checkInput() {
        if (StringUtils.isPhoneNumber(phone) && code.length() == 6) {
            tvLogin.setClickable(true);
            tvLogin.setBackgroundResource(R.drawable.login_blue_bg);
        } else {
            tvLogin.setClickable(false);
            tvLogin.setBackgroundResource(R.drawable.login_gray_bg);
        }
    }

    /**
     * 获取手机验证码
     */
    private void getMobileMsgCode() {
        HashMap hashMap = new HashMap();
        hashMap.put("phone", phone);
        hashMap.put("type", "login");//短信验证码方式 register/login
        new HttpRequest(this).doPost(UrlConstants.login_verify, "", hashMap, new HttpStringCallBack() {
            @Override
            public void onSuccess(Object result) {
                if (result instanceof BaseModel) {
                    BaseModel model = (BaseModel) result;
                    if (model.getStatus() == 200) {
                        tvGetCode.setClickable(false);
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                for (int i = 60; i > 0; i--) {
                                    handler.sendEmptyMessage(CODE_ING);
                                    if (i <= 0) {
                                        break;
                                    }
                                    try {
                                        Thread.sleep(1000);
                                    } catch (InterruptedException e) {
                                        e.printStackTrace();
                                    }
                                }
                                handler.sendEmptyMessage(CODE_REPEAT);
                            }
                        }).start();
                    } else {
                        Toast.makeText(getContext(), model.getMsg(), Toast.LENGTH_SHORT).show();
                    }
                }
            }

            @Override
            public void onFailure(int code, String msg) {

            }
        });
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case CODE_ING:
                    tvGetCode.setText(--TIME + "s后重新获取");
                    break;
                case CODE_REPEAT:
                    tvGetCode.setText("获取验证码");
                    tvGetCode.setClickable(true);
                    TIME = 60;
                    break;
                default:
                    break;
            }
        }
    };

    /**
     * 登录
     */
    private void login() {
        Map<String, String> map = new HashMap<>();
        map.put("phone", phone);
        map.put("captcha", code);
        map.put("spread", "0");
        new HttpRequest(getContext()).doPost(UrlConstants.login_code, "", map, LoginModel.class, new HttpStringCallBack() {
            @Override
            public void onSuccess(Object result) {
                if (result instanceof LoginModel) {
                    LoginModel loginModel = (LoginModel) result;
                    MethodUtils.loginAfter(LoginVerificationCodeActivity.this, phone, loginModel.getData().getToken());
                }
            }

            @Override
            public void onFailure(int code, String msg) {

            }
        });
    }
}
